package com.shenzhen.horselive.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Hashtable;

public class A {
    public enum TransparentScanDirection {
        右下方, 左上方
    }

    public static class QRCodeCompose {
        /**
         * 计算图片里的透明区域
         *
         * @param bitmap
         * @return
         */

        public Rect getTransparentBounds(Bitmap bitmap, TransparentScanDirection transparentScanDirection) {
            int pixelStep = 5;
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int left = 0, top = 0, right = 0, bottom = 0;
            boolean isContainTransparent;
            Point pointTR = null, pointBL = null;
            switch (transparentScanDirection) {
                case 右下方:
                    Point pointBR = null;
                    for (int y = height - 1; y >= 0; y -= pixelStep) {
                        isContainTransparent = false;
                        for (int x = width - 1; x >= 0; x -= pixelStep) {
                            int color = bitmap.getPixel(x, y);
                            if (pointBR != null && pointBL != null && color == 0) {
                                isContainTransparent = true;
                                break;
                            }
                            if (color == 0 && pointBR == null)
                                pointBR = new Point(x, y);
                            if (pointBL == null && pointBR != null && color != 0) {
                                pointBL = new Point(x, y);
                                isContainTransparent = true;
                                break;
                            }
                        }
                        if (pointBR != null && pointBL != null && !isContainTransparent) {
                            pointTR = new Point(0, y);
                            break;
                        }
                    }
                    if (pointBL == null || pointBR == null || pointTR == null)
                        return null;
                    left = pointBL.x;
                    top = pointTR.y;
                    right = pointBR.x;
                    bottom = pointBR.y;
                    break;
                case 左上方:
                    Point pointTL = null;
                    for (int y = 0; y < height; y += pixelStep) {
                        isContainTransparent = false;
                        for (int x = 0; x < width; x += pixelStep) {
                            int color = bitmap.getPixel(x, y);
                            if (pointTL != null && pointTR != null && color == 0) {
                                isContainTransparent = true;
                                break;
                            }
                            if (color == 0 && pointTL == null)
                                pointTL = new Point(x, y);
                            if (pointTR == null && pointTL != null && color != 0) {
                                pointTR = new Point(x, y);
                                isContainTransparent = true;
                                break;
                            }
                        }
                        if (pointTR != null && pointTL != null && !isContainTransparent) {
                            pointBL = new Point(0, y);
                            break;
                        }
                    }
                    if (pointTR == null || pointTL == null || pointBL == null)
                        return null;
                    left = pointTL.x;
                    top = pointTR.y;
                    right = pointTR.x;
                    bottom = pointBL.y;
                    break;
            }

            return new Rect(left - pixelStep, top - pixelStep, right + pixelStep, bottom + pixelStep);
        }


        /**
         * 通过透明区域合成二维码位图
         * 将watermark画到src透明区域里
         *
         * @return
         */
        Rect rect;

        public Bitmap composeQrCodeBitmapByTransparentArea(Bitmap src, Bitmap qrCode, TransparentScanDirection transparentScanDirection) {
            if (src == null || qrCode == null) {
                return null;
            }
            int w = src.getWidth();
            int h = src.getHeight();

//            .logTimeConsume("getTransparentBounds", false, () -> rect = getTransparentBounds(src, transparentScanDirection));
            //获取src的透明区域
            rect = getTransparentBounds(src, transparentScanDirection);
            if (rect == null) {
//                Util_Toast.toast("未扫描到透明区域，无法合成！");
                return src;
            }
            //将qrCode大小调整为src透明区域的大小
            int extraPixel =2;
            Bitmap newBitmap = zoomImg(qrCode, rect.right - rect.left + extraPixel, rect.bottom - rect.top + extraPixel);
            qrCode.recycle();
            qrCode = newBitmap;

            //create the new blank bitmap
            Bitmap newb = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);//创建一个新的和SRC长度宽度一样的位图
            Canvas cv = new Canvas(newb);
            //draw src into
            cv.drawBitmap(src, new Rect(0, 0, w, h), new Rect(0, 0, w, h), null);//在 0，0坐标开始画入src
            cv.drawBitmap(qrCode, rect.left, rect.top, null);

            //save all clip
            //cv.save(Canvas.ALL_SAVE_FLAG);//保存
            cv.save();//保存
            //store
            cv.restore();//存储
            return newb;
        }

        /**
         * 处理图片
         *
         * @param qrCode    所要转换的bitmap
         * @param newWidth  新的宽
         * @param newHeight 新的高
         * @return 指定宽高的bitmap
         */
        public static Bitmap zoomImg(Bitmap qrCode, int newWidth, int newHeight) {
            // 获得图片的宽高
            int width = qrCode.getWidth();
            int height = qrCode.getHeight();
            // 计算缩放比例
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;
            // 取得想要缩放的matrix参数
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            // 得到新的图片   www.2cto.com
            Bitmap newbm = Bitmap.createBitmap(qrCode, 0, 0, width, height, matrix, true);
            return newbm;
        }

        public static void saveImageToGallery(Context context, Bitmap bmp) {
            // 首先保存图片
            File appDir = new File(Environment.getExternalStorageDirectory(), "kouliang");
            String path = "";
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            String fileName = System.currentTimeMillis() + ".png";
            File file = new File(appDir, fileName);
            path = file.getPath();

            try {
                FileOutputStream fos = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.PNG, 0, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            // 其次把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 最后通知图库更新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
        }

        public Bitmap createQRCode(String str, int widthAndHeight) {
            try {
                Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
                hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
                BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
                int width = matrix.getWidth();
                int height = matrix.getHeight();
                int[] pixels = new int[width * height];

                for (int y = 0; y < height; y++) {
                    for (int x = 0; x < width; x++) {
                        if (matrix.get(x, y)) {
                            pixels[y * width + x] = Color.BLACK;
                        } else {
                            pixels[y * width + x] = Color.WHITE;
                        }
                    }
                }
                Bitmap bitmap = Bitmap.createBitmap(width, height,
                        Bitmap.Config.RGB_565);
                bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
                return bitmap;
            } catch (WriterException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
